package mianyang.zhangsan.com.utils;

import mianyang.zhangsan.com.pojo.UploadFile;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Locale;
import java.util.UUID;

public class Upload {


    public static String handlePhotoUpload(HttpServletRequest request, String uploadFile) throws IOException {
        UploadFile ret = new UploadFile();
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        //创建上传图片的存放目录（没有则创建）
        if (UploadFile.prefix == null || UploadFile.prefix == ""){
//            String imageDir = "/upload";
//            String realPath = request.getSession().getServletContext().getRealPath(imageDir);
            String realPath = new File("").getCanonicalPath() +  File.separator + "src\\main\\webapp\\upload";
            File photoSave = new File(realPath);
            if (!photoSave.exists()){
                photoSave.mkdirs();
            }
            UploadFile.prefix = realPath;
            System.out.println(realPath);
        }
        MultipartFile multipartFile = multipartRequest.getFile(uploadFile);
        if (!multipartFile.isEmpty()){
            String suffix = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf(".")).toLowerCase();
            if (!suffix.equals(".jpg")&&!suffix.equals(".gif")&&!suffix.equals(".png")){
               throw new RuntimeException("图片格式不正确!");
            }
            //创建唯一的图片名称
            String userPhotoName = UUID.randomUUID().toString() + suffix;
            //组合图片路径，并保存图片
            String completePath = ret.getCompletePath(userPhotoName);
            System.out.println(completePath);
            File userPhotoFile = new File(completePath);
            multipartFile.transferTo(userPhotoFile);
            ret.setSuffix(userPhotoName);
        }
        return ret.getSuffix();
    }
}
